package com.whu.zqm.service;

import com.whu.zqm.dao.ProductsJPARepository;
import com.whu.zqm.dao.SupplierJPARepository;
import com.whu.zqm.entity.Products;
import com.whu.zqm.entity.Supplier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductsService {

    private final ProductsJPARepository productsRepository;
    private final SupplierJPARepository supplierRepository;

    public ProductsService(ProductsJPARepository productsRepository, SupplierJPARepository supplierRepository) {
        this.productsRepository = productsRepository;
        this.supplierRepository = supplierRepository;
    }

    public Products addProduct(Products p) {
        return productsRepository.saveAndFlush(p);
    }

    public Products getProduct(long id) {
        return productsRepository.getById(id);
    }

    public void updateProducts(long id, Products p) {
        productsRepository.save(p);
    }

    public void deleteProducts(long id) {
        productsRepository.deleteById(id);
    }

    public List<Products> getProducts(){
        return productsRepository.findAll();
    }

    //Native Query
    public List<Products> findByName(String name) {
        return productsRepository.findByName(name);
    }


    //以上是基础增删改查，后面实现模糊查询等其他复杂查询方法

    //jpql查询有库存的商品
    public List<Products> getProductInStock() {
        return productsRepository.findProductsInStock();
    }

    //Paging and Sorting
    public Page<Products> getAll(Pageable pageable) {
        return productsRepository.findAll(pageable);
    }

    //supplier
    public Products addSupplier(long productId, long supplierId) {
        Products p = productsRepository.getById(productId);
        Supplier supplier = supplierRepository.getById(supplierId);
        p.getSuppliers().add(supplier);
        return productsRepository.save(p);
    }

    public Products removeSupplier(long productsId, long supplierId) {
        Products p = productsRepository.getById(productsId);
        Supplier supplier = supplierRepository.getById(supplierId);
        p.getSuppliers().remove(supplier);
        return productsRepository.save(p);
    }
}
